package psn.xshirmp.http;

import com.alibaba.fastjson.JSONObject;
import okhttp3.*;

import java.io.IOException;

/**
 * OKHttp 客户端工具，支持post、get等http请求
 *
 * @project trade
 * @time 2018/3/28 9:38
 */
public class OkHttpClientUtils {

    private static final OkHttpClient CLIENT = new OkHttpClient();
    private static final Request.Builder BUILDER = new Request.Builder();
    private static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");

    public static void get(String url) {
        Request.Builder local = BUILDER;
        local.url(url);
        run(local.build());
    }

    public static void post(String url, String body) {
        Request.Builder local = BUILDER;
        local.url(url);
        if (body != null && !body.isEmpty()) {
            local.post(RequestBody.create(JSON, body));
        }
        run(local.build());
    }

    private static Response run(Request request) {
        Response response = null;
        try {
            response = CLIENT.newCall(request).execute();
        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            if (response != null) {
                System.out.println("响应如下： " + JSONObject.toJSONString(response));
                try {
                    System.out.println("获得body数据如下： " + response.body().string());
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
        }
        return response;
    }

}
